<template>
  <div id="box" ref="pdfBox">
        <pdf
            v-for="i in numPages"
            :key="i"
            :src="pdfSrc"
            :page="i"
            id="pdf"
        >
        </pdf>
  </div>
</template>
<script>
// import pdf from 'vue-pdf'
// import Hammer from 'hammerjs'

export default {
  name: "demo",
  components: { },

  data() {
    return {
      ServerUrl: process.env.VUE_APP_BASE_API,
      pdfSrc: '',
      numPages: undefined,
      lastdeltaX: 0,
      pdfh5: null
    };
  },
  mounted() {
    // this.pdfSrc = this.ServerUrl + '/file/export/pdf?fileid=' + this.info.id + '#toolbar=0'
    this.pdfSrc = 'http://www.ccvi.top:6008/file/export/pdf?fileid=844#toolbar=0'
    // this.getNumPages()
    // this.aaa()
    // const el = document.getElementById('pdf')
    // this.hammerIt(el)
    // this.setPinch()
    this.pdfh5 = new Pdfh5("#demo", {
      pdfurl: "http://www.ccvi.top:6008/file/export/pdf?fileid=844#toolbar=0"
    });
    //监听完成事件
    this.pdfh5.on("complete", function (status, msg, time) {
      console.log("状态：" + status + "，信息：" + msg + "，耗时：" + time + "毫秒，总页数：" + this.totalNum)
    })
  },
  methods: {
    getNumPages() {
      // console.log(this.pdfSrc)
      this.$loading.show();
      let loadingTask = pdf.createLoadingTask(this.pdfSrc)
      loadingTask.promise.then(pdf => {
        console.log(pdf)
        this.numPages = pdf.numPages
        this.$loading.hide();
      }).catch(err => {
        console.error('pdf 加载失败', err);
      })
    },
    hammerIt(elm) {
      console.log(elm)
      let hammertime = new Hammer(elm, {});
      hammertime.get('pinch').set({
        enable: true
      });
      var posX = 0,
          posY = 0,
          scale = 1,
          last_scale = 1,
          last_posX = 0,
          last_posY = 0,
          max_pos_x = 0,
          max_pos_y = 0,
          transform = "",
          el = elm;

      hammertime.on('doubletap pan pinch panend pinchend', function(ev) {
        if (ev.type === "doubletap") {
          transform =
              "translate3d(0, 0, 0) " +
              "scale3d(2, 2, 1) ";
          scale = 2;
          last_scale = 2;
          try {
            if (window.getComputedStyle(el, null).getPropertyValue('-webkit-transform').toString() != "matrix(1, 0, 0, 1, 0, 0)") {
              transform =
                  "translate3d(0, 0, 0) " +
                  "scale3d(1, 1, 1) ";
              scale = 1;
              last_scale = 1;
            }
          } catch (err) {
            console.log(err)
          }
          el.style.webkitTransform = transform;
          transform = "";
        }

        //pan
        if (scale != 1) {
          posX = last_posX + ev.deltaX;
          posY = last_posY + ev.deltaY;
          max_pos_x = Math.ceil((scale - 1) * el.clientWidth / 2);
          max_pos_y = Math.ceil((scale - 1) * el.clientHeight / 2);
          if (posX > max_pos_x) {
            posX = max_pos_x;
          }
          if (posX < -max_pos_x) {
            posX = -max_pos_x;
          }
          if (posY > max_pos_y) {
            posY = max_pos_y;
          }
          if (posY < -max_pos_y) {
            posY = -max_pos_y;
          }
        }


        //pinch
        if (ev.type === "pinch") {
          console.log(123)
          scale = Math.max(.999, Math.min(last_scale * (ev.scale), 4));
        }
        if(ev.type === "pinchend"){last_scale = scale;}

        //panend
        if(ev.type === "panend"){
          last_posX = posX < max_pos_x ? posX : max_pos_x;
          last_posY = posY < max_pos_y ? posY : max_pos_y;
        }

        if (scale != 1) {
          transform =
              "translate3d(" + posX + "px," + posY + "px, 0) " +
              "scale3d(" + scale + ", " + scale + ", 1)";
        }

        if (transform) {
          el.style.webkitTransform = transform;
        }
      });
    },
    aaa() {
      var hammertime = new Hammer(document.getElementById('box'), {
        transform_always_block: true,
        transform_min_scale: 1,
        drag_block_horizontal: false,
        drag_block_vertical: false,
        drag_min_distance: 0
      });

      var rect = document.getElementById('pdf');

      let scale = 1, last_scale, rotation = 1, last_rotation;

      hammertime.on('touch drag transform',function(ev){
        switch(ev.type){
          case 'touch':
            last_scale = scale ;
            last_rotation = rotation;
            break;
            // case'drag':
            // posX = ev.gesture.deltaX;
            // posY = ev.gesture. deltaY;
            // break;
          case'transform':
            rotation = last_rotation + ev.gesture.rotation;
            scale = Math.max(1,Math.min (last_scale * ev.gesture.scale, 10));
            break;
        }

        // transform！
        var transform =
            //" translate3d（"+ posX +"px，"+ posY +"px，0）"+
            "scale3d（"+ scale +"，"+ scale +"，0）";
        rect.style.transform = transform;
        rect.style.oTransform = transform;
        rect.style.msTransform = transform;
        rect.style.mozTransform = transform;
        rect.style.webkitTransform = transform;
      });
    },
    // 启动缩放功能
    setPinch() {
      let that = this;
      let oldScale = 1;
      let oBox = document.querySelector("#box");//获取到需要缩放的元素
      let hammer = new Hammer(oBox);

//设置移动的方向
      hammer.get("pan").set({
        direction: Hammer.DIRECTION_ALL
      });
//移动开始时  先计算限制的范围
      hammer.on("panstart", function() {
        clearTimeout(that.timerOut);
        that.showFixed = true;
        let minX = that.$refs.pdfBox.offsetWidth * that.nowScale * that.OriginX - that.$refs.pdfBox.offsetWidth * that.OriginX;
        let maxX = that.$refs.pdfBox.offsetWidth * that.nowScale - minX - that.$refs.pdfBox.offsetWidth;
        let minY = that.$refs.pdfBox.offsetHeight * that.nowScale * that.OriginY - that.$refs.pdfBox.offsetHeight * that.OriginY;
        let maxY = that.$refs.pdfBox.offsetHeight * that.nowScale - minY - ((that.$refs.pdfBox.offsetHeight / that.page_count) - 50);
        that.minY = minY;
        that.maxY = maxY;
        oBox.style.transitionDuration = "0s";
        hammer.on("panmove", function(event) {
          let x = 0;
          let y = 0;
          if (parseFloat(that.lastdeltaX + event.deltaX) > minX) {
            x = minX;
          } else if (parseFloat(that.lastdeltaX + event.deltaX) < -maxX) {
            x = -maxX;
          } else {
            x = parseFloat(that.lastdeltaX + event.deltaX);
          }

          if (parseFloat(that.lastdeltaY + event.deltaY) > minY) {
            y = minY;
          } else if (parseFloat(that.lastdeltaY + event.deltaY) < -maxY) {
            y = -maxY;
          } else {
            y = parseFloat(that.lastdeltaY + event.deltaY);
          }
//用transform 来进行元素的偏移
          oBox.style.transform = "translate(" + x + "px," + y + "px)" + "scale(" + that.nowScale + ")";
        });
      });
//移动结束后  计算velocityY手指滑动的速度  时间是500ms移动到最后的位置
      hammer.on("panend", function(event) {
        that.timerOut = setTimeout(() => {
          if (that.showFixed) {
            that.showFixed = false;
          }
        }, 3000);
        let y = 0;
        let x = 0;
        let minX = that.$refs.pdfBox.offsetWidth * that.nowScale * that.OriginX - that.$refs.pdfBox.offsetWidth * that.OriginX;
        let maxX = that.$refs.pdfBox.offsetWidth * that.nowScale - minX - that.$refs.pdfBox.offsetWidth;
        let minY = that.$refs.pdfBox.offsetHeight * that.nowScale * that.OriginY - that.$refs.pdfBox.offsetHeight * that.OriginY;
        let maxY = that.$refs.pdfBox.offsetHeight * that.nowScale - minY - ((that.$refs.pdfBox.offsetHeight / that.page_count) - 50);
        that.minY = minY;
        that.maxY = maxY;
        that.lastdeltaX = parseFloat(that.lastdeltaX + event.deltaX);
        that.lastdeltaY = parseFloat(that.lastdeltaY + event.deltaY);
        let distance = event.velocityY * 500;
        oBox.style.transitionDuration = "500ms";
        if (that.lastdeltaX > minX) {
          x = minX;
        } else if (that.lastdeltaX < -maxX) {
          x = -maxX;
        } else {
          x = that.lastdeltaX;
        }

        if (that.lastdeltaY + distance > minY) {
          y = minY;
        } else if (that.lastdeltaY + distance < -maxY) {
          y = -maxY;
        } else {
          y = that.lastdeltaY + distance;
        }
        oBox.style.transform = "translate(" + x + "px," + y + "px)" + "scale(" + that.nowScale + ")";
        that.lastdeltaY = y;
        that.lastdeltaX = x;
      });
//开启缩放
      hammer.get("pinch").set({
        enable: true
      });
//缩放开始时计算缩放的原点transformOrigin
      hammer.on("pinchstart", function(event) {
        oldScale = that.nowScale || 1;
        oBox.style.transitionDuration = "200ms";
        oBox.style.transitionTimingFunction = "cubic-bezier(0.23, 1, 0.32, 1)";
        that.OriginX = Math.abs(event.center.x - that.lastdeltaX) / (that.$refs.pdfBox.offsetWidth);
        that.OriginY = Math.abs(event.center.y - that.lastdeltaY) / (that.$refs.pdfBox.offsetHeight);
        oBox.style.transformOrigin = Math.abs(event.center.x - that.lastdeltaX) / (that.$refs.pdfBox.offsetWidth) * 100 + "%" + " "
            + Math.abs(event.center.y - that.lastdeltaY) / (that.$refs.pdfBox.offsetHeight) * 100 + "%";
//限制缩放范围是2.5~1
        hammer.on("pinchmove", function(event) {
          if (2.5 > oldScale * event.scale && oldScale * event.scale > 0.9) {
            that.nowScale = oldScale * event.scale;
            oBox.style.transform = "translate(" + parseFloat(that.lastdeltaX) + "px," + parseFloat(that.lastdeltaY) + "px)" + "scale(" + oldScale * event.scale + ")";
          }
        });
      });
      hammer.on("pinchend", function(event) {
        oBox.style.transitionDuration = "0s";
        if (oldScale * event.scale < 1) {
          that.nowScale = 1;
          oBox.style.transform = "translate(" + parseFloat(that.lastdeltaX) + "px," + parseFloat(that.lastdeltaY) + "px)" + "scale(" + 1 + ")";
        }

        if (oldScale * event.scale > 2) {
          that.nowScale = 2;
          oBox.style.transform = "translate(" + parseFloat(that.lastdeltaX) + "px," + parseFloat(that.lastdeltaY) + "px)" + "scale(" + 2 + ")";
        }

      });
    },
  }
}
</script>

<style scoped>
#box{
  width: 100%;

}
</style>